package com.kaibes.orm.core.listener;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;

import com.kaibes.core.base.util.StringUtils;

public class MapCacheListener<E> implements CacheListener<E> {

    private Map<String, List<?>> cacheMap;
    private Map<String, Long> countMap;
    private Function<Object, String> keyFunction;

    public MapCacheListener(Function<Object, String> keyFunction) {
        this.keyFunction = keyFunction;
        cacheMap = new ConcurrentHashMap<>();
        countMap = new ConcurrentHashMap<>();
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> List<T> get(Object select) throws SQLException {
        String key = keyFunction.apply(select);
        if (StringUtils.isNotEmpty(key)) {
            return (List<T>) cacheMap.get(key);
        }
        return null;
    }

    @Override
    public void set(Object select, List<?> dataList) throws SQLException {
        String key = keyFunction.apply(select);
        if (StringUtils.isNotEmpty(key)) {
            cacheMap.put(key, dataList);
        }
    }

    @Override
    public Long getCount(Object select) throws SQLException {
        String key = keyFunction.apply(select);
        if (key != null && countMap.containsKey(key)) {
            return countMap.get(key);
        }
        return null;
    }
    
    @Override
    public void setCount(Object select, Long count) throws SQLException {
        String key = keyFunction.apply(select);
        if (key != null) {
            countMap.put(key, count);
        }
    }

    @Override
    public void clear() throws SQLException {
        cacheMap.clear();
        countMap.clear();
    }

}
